package org.example.AI;

/**
 * @author: 默苍璃
 * @date: 2024-07-18 16:46
 */
public class BotContext {
    private State state = new DisconnectedState();
    private int busyCount = 0; // 用于跟踪是否忙碌的计数器

    public String chat(String input) {
        if ("hello".equalsIgnoreCase(input)) {
            state.exit(this);
            state = new ConnectedState();
            state.enter(this);
            return state.init();
        } else if ("bye".equalsIgnoreCase(input)) {
            state.exit(this);
            state = new DisconnectedState();
            state.enter(this);
            return state.init();
        }

        if (isBusy()) {
            state = new BusyState();
            state.enter(this);
            return state.init();
        }

        String response = state.reply(input);

        // 如果需要，更新忙碌状态
        updateBusyStatus();

        return response;
    }

    private boolean isBusy() {
        return busyCount > 0;
    }

    private void updateBusyStatus() {
        // 检查当前状态是否需要切换到忙碌状态
        if (!state.getClass().equals(BusyState.class) && isBusy()) {
            state.exit(this);
            state = new BusyState();
            state.enter(this);
        } else if (state.getClass().equals(BusyState.class) && !isBusy()) {
            state.exit(this);
            state = new ConnectedState(); // 假设在忙碌状态结束后回到连接状态
            state.enter(this);
        }
    }

    public void startTask() {
        busyCount++;
        updateBusyStatus();
    }

    public void endTask() {
        if (busyCount > 0) {
            busyCount--;
        }
        updateBusyStatus();
    }

    public void simulateLongRunningTask() {
        startTask();
        // try {
        //     Thread.sleep(2000); // 模拟一个耗时2秒的任务
        // } catch (InterruptedException e) {
        //     Thread.currentThread().interrupt();
        //     throw new RuntimeException(e);
        // } finally {
        //     endTask();
        // }
    }


}